package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.controller.LogicController;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

@Api(tags = "用户实体控制器")
@RequestMapping("/user")
@RestController
public class UserController extends LogicController<UserService, UserDao, User, Long> {

    public UserController(@Autowired UserService service) {
        super(service);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseEntity<?> login(
            @ApiParam("用户名") @RequestParam String username,
            @ApiParam("密码") @RequestParam String password) {
        try {
            Map<String, Object> result = getService().login(username, password);
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", "登录成功",
                    "data", result
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "code", 400,
                    "message", e.getMessage()
            ));
        }
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ResponseEntity<?> register(@Valid @RequestBody User user) {
        try {
            User registeredUser = getService().register(user);
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", "注册成功"
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "code", 400,
                    "message", e.getMessage()
            ));
        }
    }
}
